<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
    <el-form-item label="原密码" prop="oldPassword">
      <el-input v-model="form.oldPassword" type="password"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="form.newPassword" type="password"></el-input>
    </el-form-item>
    <el-form-item label="确认新密码" prop="confirmPassword">
      <el-input v-model="form.confirmPassword" type="password"></el-input>
    </el-form-item>
  </el-form>
  <div class="dialog-footer">
    <el-button type="primary" @click="handleSubmit">修改密码</el-button>
    <el-button @click="close">取 消</el-button>
  </div>
</template>


<script lang="ts" setup>
import {
  ElForm,
  ElInput,
  ElMessage,
} from 'element-plus'
import userApi from "@/api/acl/user";

import { ref, reactive } from 'vue'
import useCloseTag from "@/hooks/useCloseTag";

const { closeTag } = useCloseTag()

const formRef = ref(ElForm);

const form = ref({})

/**
 * 判断两次输入是否一致
 * @param rule 
 * @param value 
 * @param callback 
 */
const confirmPasswordValidator = (rule: any, value: any, callback: any) => {

  if (value !== form.value.newPassword) {
    return callback(new Error('确认密码不一致！！！！'))
  }
  return callback()
}

/**
 * 旧密码是否正确
 */
const oldPasswordValidator = (rule: any, value: any, callback: any) => {

  userApi.equlasOldPwd(value).then(({ data }) => {
    return data ? callback() : callback(new Error('密码错误！！！！'))
  })

}

const rules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { validator: oldPasswordValidator, trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: confirmPasswordValidator, trigger: 'blur' }
  ]
})


/**
 * 保存新密码
 */
/**
 * 表单提交
 */
const handleSubmit = () => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      // 更新操作
      userApi.updatePwd({
        oldPassword: form.value.oldPassword,
        newPassword: form.value.newPassword
      })
        .then(() => {
          ElMessage.success("修改成功");
          closeTag.value();
        })


    }
  });
}

/**
 * 取消修改
 */
const close = () => {
  closeTag.value()
}



</script>